package cn.summit.serialization.adapter;

import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

/**
 * @author summit
 * @since 2020/11/18 9:09
 */
public class LongAdapter extends TypeAdapter<Long> {

    public static final Long MAX_SAFE_INTEGER = 9007199254740991L;

    @Override
    public void write(JsonWriter out, Long value) throws IOException {
        if (value != null) {
            if (value > MAX_SAFE_INTEGER) {
                out.value(value.toString());
            } else {
                out.value(value);
            }
        }else {
            out.nullValue();
        }
    }

    @Override
    public Long read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }
        try {
            String result = in.nextString();
            if ("".equals(result)) {
                return null;
            }
            return Long.parseLong(result);
        } catch (NumberFormatException e) {
            throw new JsonSyntaxException(e);
        }
    }
}